package protocol;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.simple.JSONObject;

public class HTTPMSG implements HTTPPartInterface {
	private String _msg;
	private JSONObject _asJSON;

	public JSONObject getJSON() {
		return _asJSON;
	}

	public HTTPMSG(String msg) {
		_asJSON = null;
		String ResultString = new String();
		Pattern regex = Pattern.compile("(\n\n|\r\n\r\n)(.*)",
				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
						| Pattern.DOTALL | Pattern.MULTILINE);
		Matcher regexMatcher = regex.matcher(msg);
		if (regexMatcher.find()) {
			ResultString = regexMatcher.group(2);
		}
		if (ResultString.length() == 0 && msg.length() > 0) {
			ResultString = msg;
		}
		String resultString2 = ResultString.replaceAll(
				"(?ism)(\n|\r\n)$|^(\n|\r\n)", "");
		this._msg = resultString2;
	}

	public String toString() {
		return java.net.URLEncoder.encode(this._msg);
	}

	@SuppressWarnings("unchecked")
	public JSONObject toJSONObject() {
		if (_asJSON == null) {
			JSONObject ret = new JSONObject();
			int unknowns = 0;
			String[] args = this._msg.split("&");
			for (String arg : args) {
				String[] splittedArg = arg.split("=");
				if (splittedArg.length != 2) {
					ret.put("unknown" + unknowns, arg);
					unknowns++;
				} else {
					ret.put(splittedArg[0], splittedArg[1]);
				}
			}
			this._asJSON = ret;
		}
		return this._asJSON;
	}

	@Override
	public boolean isValid() {
		// TODO Auto-generated method stub
		return true;
	}
}
